/**
 * Copyright 2018 orivil.com. All rights reserved.
 * Use of this source code is governed by a MIT-style
 * license that can be found at https://mit-license.org.
 */

package image

import (
	"os"
	"time"
	"gitee.com/tugoer/orivil/bundles/db"
	"github.com/jinzhu/gorm"
)

func init() {
	db.Gorm.AutoMigrate(&Image{})
}

type Image struct {
	ID int
	Url string
	Label string `gorm:"index"`
	CreatedAt int64 `gorm:"index"`
}

func GetImage(id int) (img *Image) {
	img = &Image{
		ID: id,
	}
	db.Gorm.First(img)
	return img
}

func (i *Image) Create() error {
	i.CreatedAt = time.Now().Unix()
	return db.Gorm.Create(i).Error
}

func (i *Image) Delete() error {
	exist := &Image{ID: i.ID}
	err := db.Gorm.First(exist).Error
	if err != nil {
		return err
	}
	err = os.Remove(exist.Url)
	if err != nil {
		return err
	}
	return db.Gorm.Delete(i).Error
}

func parseQuery(start, end *time.Time, label string, gdb *gorm.DB) *gorm.DB {
	var query string
	var args []interface{}
	if label != "" {
		query = "label=?"
		args = []interface{}{label}
	}
	if start != nil {
		if query != "" {
			query += " AND "
		}
		query += "created>=?"
		args = append(args, start.Unix())
	}
	if end != nil {
		if query != "" {
			query += " AND "
		}
		query += "created<=?"
		args = append(args, end.Unix())
	}
	if query != "" {
		gdb = gdb.Where(query, args...)
	}
	return gdb
}

func QueryImage(start, end *time.Time, label string, desc bool, limit, offset int) []*Image {
	var imgs []*Image
	var order = "id asc"
	if desc {
		order = "id desc"
	}
	model := parseQuery(start, end, label, db.Gorm.Model(&Image{}))
	model.Order(order).Limit(limit).Offset(offset).Find(&imgs)
	return imgs
}

func CountImage(start, end *time.Time, label string) int {
	var count int
	model := parseQuery(start, end, label, db.Gorm.Model(&Image{}))
	model.Count(&count)
	return count
}
